﻿Imports System.IO
Imports System.Data
Imports System.Data.OleDb
Imports System.Reflection

Public Class frmAddRepository
    Dim _strNameFileIni As String 'Nombre para el archivo de inicio
    Dim _strProviderDB As String 'Nombre para el proveedor de datos elegido
    Dim _strPathFileIni As String 'Ruta para el archivo de incio
    Dim StrCn As String = ""
    Const ConsStrNuevaDb = "[Nueva Base de Datos]"

    
    Private Sub btnPathFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPathFile.Click
        If Not txtNombreRepository.Text.Length > 0 Then
            txtNombreRepository.Focus()
            ErrorProvider1.SetError(txtNombreRepository, "Por favor escriba un nombre para el repositorio.")
            Exit Sub
        End If
        If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            ErrorProvider1.Clear()
            FolderBrowserDialog1.Description = "Por Favor seleccione la carpeta donde se guardará el archivo de inicio."
            txtPathFile.Text = (FolderBrowserDialog1.SelectedPath) '& "\"  & txtNombreRepository.Text & g_StrRepositoryFileExtension
            _strPathFileIni = FolderBrowserDialog1.SelectedPath
        End If
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub

    Private Sub txtNombreRepository_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtNombreRepository.KeyPress
        Call soloAlfanumerico(e)
    End Sub

    Private Sub txtPathDocuments_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtPathDocuments.KeyPress
        'e.Handled = True
    End Sub

    Private Sub txtPathFile_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtPathFile.KeyPress
        'e.Handled = True
    End Sub

    Private Sub btnPathDocuments_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPathDocuments.Click
        If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            FolderBrowserDialog1.Description = "Por Favor seleccione la carpeta donde se guardará el archivo de inicio."
            txtPathDocuments.Text = (FolderBrowserDialog1.SelectedPath)
            g_StrPathDocument = FolderBrowserDialog1.SelectedPath
        End If
    End Sub

    Private Sub btnSetUserConnectFolfer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSetUserConnectFolfer.Click
        frmSetAccount.ShowDialog()
    End Sub

    Private Sub cboDataSource_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) 'Handles cboDataSource.SelectedIndexChanged
        If cboDataSource.SelectedIndex <> -1 Then
            If cboDataSource.SelectedIndex <> 0 Then
                gbxServerParameters.Visible = True
                rbdWindowsAutenthication.Checked = True
                'Me.cboDatabase.SelectedIndex = 0

                Select Case cboDataSource.SelectedIndex
                    Case 1
                        _strProviderDB = "SQLOLEDB"

                End Select

            Else
                gbxServerParameters.Visible = False
            End If
        Else
            'ErrorProvider1.SetError(cboDataSource, "por favor seleccione una fuente de Datos de la lista.")
        End If

    End Sub

    Private Sub frmAddRepository_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        AddHandler cboDataSource.SelectedIndexChanged, _
        AddressOf cboDataSource_SelectedIndexChanged
        cboDataSource.SelectedIndex = 1

    End Sub

    Private Sub btnTestConnection_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTestConnection.Click  ', cboDatabase.MouseClick
        Call ProbrarConexion()
    End Sub
    Function ProbrarConexion(Optional ByVal BolMensajeExito As Boolean = True) As Boolean

        If cboDataSource.SelectedIndex = 1 Then
            If rbdWindowsAutenthication.Checked Then
                StrCn = "provider=" & _strProviderDB & ";Data Source=" & txtServerRepository.Text & ";Integrated Security=SSPI"
            End If
            If rdbAutenticationBD.Checked Then
                StrCn = "provider=" & _strProviderDB & ";Persist Security Info=False;User ID=" & txtUser.Text & ";Password=" & txtPassword.Text & ";Data Source=" & txtServerRepository.Text
            End If
        ElseIf cboDataSource.SelectedIndex = 2 Then
            _strProviderDB = "OraOLEDB.Oracle"
            StrCn = "provider=" & _strProviderDB & ";Persist Security Info=False;User ID=" & txtUser.Text & ";Password=" & txtPassword.Text & ";Data Source=" & txtServerRepository.Text
            'End If
        End If

        If TestDb(StrCn, True) Then
            If cboDatabase.Items.Count < 1 Then
                LoadCombo(StrCn)
            End If
            If BolMensajeExito Then
                MessageBox.Show(g_StrMessageBoxDialog, "Conexión correcta.", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
            Return True
        Else
            MessageMistake(g_StrMessageBoxDialog)
            Return False
        End If

    End Function

    Private Sub LoadCombo(ByVal strCn As String)
        Dim table As DataTable = GetLisDataBasesSQL(strCn)
        'Dim list As New ArrayList

        cboDatabase.Items.Insert(0, ConsStrNuevaDb)
        For i As Int16 = 0 To table.Rows.Count - 1
            cboDatabase.Items.Insert(i + 1, table.Rows(i).Item("DATABASE_NAME"))
        Next

        cboDatabase.SelectedIndex = 0

    End Sub
    Private Sub AddItem(ByVal list As IList, ByVal type As Type, _
                        ByVal displayMember As String, ByVal displayText As String)
        Dim obj As Object = Activator.CreateInstance(type)
        Dim displayProperty As PropertyInfo = type.GetProperty(displayMember)
        displayProperty.SetValue(obj, displayText, Nothing)
        'Dim valueProperty As PropertyInfo = type.GetProperty(valueMember)
        'valueProperty.SetValue(obj, "-1", Nothing)
        list.Insert(0, obj)
    End Sub



    Private Sub rdbAutenticationBD_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdbAutenticationBD.CheckedChanged
        If rdbAutenticationBD.Checked Then
            txtUser.Enabled = True
            txtPassword.Enabled = True
            txtUser.Focus()
            txtUser.SelectAll()
        Else
            txtUser.Enabled = False
            txtPassword.Enabled = False
        End If

    End Sub
    Function ExisteBaseDatos(ByVal StrBaseDatos As String) As Boolean
        Dim IntContador As Integer
        For IntContador = 0 To cboDatabase.Items.Count - 1
            If StrBaseDatos = cboDatabase.Items(IntContador) Then
                Return True
            End If
        Next


    End Function
    Private Sub btnCreateRepository_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateRepository.Click

        Dim StrBaseNueva As String
        If cboDatabase.Text.Trim <> "" And cboDatabase.Text <> ConsStrNuevaDb Then
            StrBaseNueva = cboDatabase.Text
        Else
            StrBaseNueva = txtNombreRepository.Text.Replace(" ", "")
        End If

        If Not ProbrarConexion(False) Then
            Exit Sub
        End If

        If ExisteBaseDatos(StrBaseNueva) Then
            MessageBox.Show("La base de datos [" & StrBaseNueva & "] ya existe.", "Error al crear base de datos.", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End If

        If ValidaForm() Then
            Try

                If CreateFileRepository(txtNombreRepository.Text, _strPathFileIni, g_StrPathDocument, _
                                        cboDataSource.SelectedIndex, returnNewPathDB(StrBaseNueva), StrBaseNueva) Then
                    MsgBox("La base de datos [" & txtNombreRepository.Text & "] se creo correctamente.", vbInformation, g_ApplicationName)
                End If
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, g_ApplicationName)
            End Try
        End If
    End Sub

    Function returnNewPathDB(ByVal StrBaseDatosNombre As String) As String
        Dim _StrNewPathDB As String = ""
        If cboDataSource.SelectedIndex = TypeBD.ACCESS Then
            _StrNewPathDB = g_StrPathDocument & "\" & txtNombreRepository.Text.Trim
        ElseIf cboDataSource.SelectedIndex = TypeBD.SQL Then
            If cboDatabase.Text = ConsStrNuevaDb Or cboDatabase.Text.Trim = "" Then
                _StrNewPathDB = "provider=" & _strProviderDB & " ;Persist Security Info=False;User ID=" & txtUser.Text _
                    & ";Pwd=" & txtPassword.Text & ";Initial Catalog=" & StrBaseDatosNombre _
                    & ";Data Source=" & txtServerRepository.Text
            Else
                _StrNewPathDB = "provider=" & _strProviderDB & " ;Persist Security Info=False;User ID=" & txtUser.Text _
                    & ";Pwd=" & txtPassword.Text & ";Initial Catalog=" & "master" _
                    & ";Data Source=" & txtServerRepository.Text
            End If
        Else
            _StrNewPathDB = "provider=" & _strProviderDB & " ;Persist Security Info=False;User ID=" & txtUser.Text _
                & ";Password=" & txtPassword.Text & ";Data Source=" & txtServerRepository.Text
        End If

        Return _StrNewPathDB

    End Function

    Function GetStringConnection(Optional ByVal typeBD As Int16 = Nothing) As String()
        Dim strConnection(2) As String


        If typeBD = 1 Then
            strConnection(0) = "MyConnectionSQL" ', _
            strConnection(1) = String.Format("Data Source={0}; User ID={1};Password={2};Initial Catalog={3}", _
                           "DESARROLLO\SQLEXPRESS", "sa", "1234", "ScanFlowNet")
            strConnection(2) = "System.Data.SqlClient"
        ElseIf typeBD = 2 Then
            strConnection(0) = "MyConnectionOracle"
            strConnection(1) = String.Format("Data Source={0};Persist Security Info=True; User ID={1};Password={2}", _
                          "XE", "scott", "cibertec")
            strConnection(2) = "System.Data.OracleClient"
        ElseIf typeBD = 3 Then
            strConnection(0) = "MyConnectionAccess"
            strConnection(1) = String.Format("Provider={0};Data Source={1}", _
                          "Microsoft.Jet.OLEDB.4.0", "C:\Program Files\ScanFlow\ScanFlow.mdb")
            strConnection(2) = "System.Data.OleDb"
        End If

        Return strConnection
    End Function

    Private Sub SetNombreVolumenDefault(ByVal StrArchivoDb As String, ByVal StrVolumen As String, ByVal StrTipoDbNew As Int16)
        Dim da As OleDbDataAdapter
        Dim StrTmpConection As String
        If StrTipoDbNew = 0 Then 'AccessDataBase Then
            StrTmpConection = g_StrProviderAccessDB & "Data Source=" & StrArchivoDb & ";"
        Else
            StrTmpConection = StrArchivoDb
        End If
        Try
            da = New OleDbDataAdapter("insert into Volumenes(Volumenid,Path,Estado) values ('" & "Volumen1','" & StrVolumen & "','1')", StrTmpConection)
            da.Dispose()
        Catch ex As Exception
            MessageMistake(Err.Description)
        End Try

    End Sub

    Function ValidaForm() As Boolean
        Dim IntIndex As Integer
        Dim strRuta As String
        Dim strRutaFile As String

        If Trim(Replace(txtNombreRepository.Text, "'", "")) = "" Then
            MsgBox("Ingrese el titulo de la base de datos", vbInformation, g_ApplicationName)
            Exit Function
        Else
            _strNameFileIni = txtNombreRepository.Text
        End If

        If Trim(Replace(txtPathFile.Text, "'", "")) = "" Then
            MsgBox("Ingrese la ruta Para el Archivo de Inicio", vbInformation, g_ApplicationName)
            Exit Function
        Else
            _strPathFileIni = txtPathFile.Text
        End If

        If Trim(Replace(txtPathDocuments.Text, "'", "")) = "" Then
            MsgBox("Ingrese la ruta de la base de datos", vbInformation, g_ApplicationName)
            Exit Function
        Else
            g_StrPathDocument = txtPathDocuments.Text
        End If

        strRutaFile = Mid(txtPathFile.Text, 1, InStrRev(txtPathFile.Text, "\"))

        If Not Directory.Exists(strRutaFile) Then
            If MsgBox("La carpeta " & strRutaFile & " no existe" & vbCrLf & _
                        "Desea Crearla ?", vbQuestion + vbYesNo, g_ApplicationName) = vbYes Then
                Directory.CreateDirectory(strRutaFile)
            Else
                Exit Function
            End If
        End If

        IntIndex = InStrRev(txtPathDocuments.Text, "\")
        strRuta = Mid(txtPathDocuments.Text, 1, IntIndex)

        If Not Directory.Exists(strRuta) Then
            If MsgBox("La carpeta " & strRuta & " no existe" & vbCrLf & _
                        "Desea Crearla ?", vbQuestion + vbYesNo, g_ApplicationName) = vbYes Then
                Directory.CreateDirectory(strRuta)
            Else
                Exit Function
            End If
        End If

        If cboDataSource.SelectedIndex < 0 Then
            MsgBox("Por favor elija una base de datos", MsgBoxStyle.Exclamation, g_ApplicationName)
            cboDatabase.Focus()
            Exit Function
        End If

        'Valida datos de servidor SQL
        If (cboDataSource.SelectedIndex = 1 Or cboDataSource.SelectedIndex = 2) And rdbAutenticationBD.Checked Then
            'Valida ingreso del servidor
            If Trim(txtServerRepository.Text) = "" Then
                MsgBox("Ingrese el nombre del servidor " & cboDataSource.Text & ".", vbExclamation, g_ApplicationName)
                Exit Function
            End If
            'Valida ingreso del usuario DB
            If Trim(txtUser.Text) = "" Then
                MsgBox("Ingrese el nombre de usuario.", vbExclamation, g_ApplicationName)
                Exit Function
            End If
        End If

        ValidaForm = True
    End Function

    Private Sub cboDataSource_SelectedIndexChanged_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboDataSource.SelectedIndexChanged

    End Sub
End Class